<template>
    <Editor
        api-key="no-api-key"
        v-model="value"
        :init="options"
        v-bind="rest"
    />
</template>

<script setup lang="ts">
    import encodeURI2 from "@/utils/encodeURI";
    // import { uploadQiniu } from "@ms/components/src/views/FileUpload/qiniuOss";
    import globalService from "@/service/global.service";
    import Editor from "@tinymce/tinymce-vue";

    // import tencentOss from "./tencentOss";
    import tinymce, { type EditorOptions } from "tinymce/tinymce";

    import "tinymce/models/dom";
    import "tinymce/themes/silver/theme";
    import "tinymce/icons/default/icons";
    import "tinymce/plugins/emoticons/js/emojis";
    import "tinymce/plugins/advlist";
    import "tinymce/plugins/autolink";
    import "tinymce/plugins/link";
    import "tinymce/plugins/image";
    import "tinymce/plugins/lists";
    import "tinymce/plugins/charmap";
    import "tinymce/plugins/preview";
    import "tinymce/plugins/anchor";
    import "tinymce/plugins/pagebreak";
    import "tinymce/plugins/searchreplace";
    import "tinymce/plugins/wordcount";
    import "tinymce/plugins/visualblocks";
    import "tinymce/plugins/visualchars";
    import "tinymce/plugins/code";
    import "tinymce/plugins/fullscreen";
    import "tinymce/plugins/insertdatetime";
    import "tinymce/plugins/media";
    import "tinymce/plugins/table";
    import "tinymce/plugins/emoticons";
    import "tinymce/plugins/template";
    // import "tinymce/plugins/help";
    // import "tinymce/plugins/help/plugin";
    // import "tinymce/plugins/help/js/i18n/keynav/en";
    // import "tinymce/plugins/help/js/i18n/keynav/zh_CN";

    import { onMounted, computed } from "vue";
    export interface IPropTypes {
        apiKey?: string;
        cloudChannel?: string;
        id?: string;
        init?: EditorOptions;
        initialValue?: string;
        outputFormat?: "html" | "text";
        inline?: boolean;
        modelEvents?: string[] | string;
        plugins?: string[] | string;
        tagName?: string;
        toolbar?: string[] | string;
        modelValue?: string;
        disabled?: boolean;
        tinymceScriptSrc?: string;
        ossFolder?: string;
    }

    // const props = withDefaults(defineProps<IPropTypes>(), {
    //     modelEvents: "",
    //     plugins: "",
    //     toolbar: "",
    // });
    const props = defineProps<IPropTypes>();
    const { init, modelValue, ossFolder, ...rest } = props;

    console.log(rest);

    const emit = defineEmits(["update:modelValue"]);

    const upload = async (files: any[]) => {
        // const res: any = await tencentOss(
        //     files,
        //     "nbd-auth-config",
        //     function (data: any) {},
        // );
        // let url = res.Location.replace(
        //     "nbd-luyan-1252627319.cos.ap-shanghai.myqcloud.com",
        //     "https://nbd-luyan-1252627319.file.myqcloud.com",
        // );
        // return url;

        // let res: any = await uploadQiniu(files[0], ossFolder);
        // let res1 = await globalService.link(res.key);
        // let data = res1.data.result.data;

        // return data;

        return "";
    };
    // const prefix = process.env.VUE_APP_PREFIX
    //     ? process.env.VUE_APP_MODE == "productionTest"
    //         ? "http://10.20.5.34:32040"
    //         : process.env.VUE_APP_MODE == "production"
    //         ? "https://mrc-saas.hxkjmedia.com"
    //         : "https://gray-mrc-saas.hxkjmedia.com"
    //     : `http://192.168.21.124:6600`;

    // const prefix = process.env.VUE_APP_FRONTEND_PREFIX;
    const prefix = import.meta.env.VITE_APP_FRONTEND_PREFIX;

    const defalutOptions = {
        base_url: prefix,
        language_url: prefix + "/tinymce/langs/zh-Hans.js",
        language: "zh-Hans",
        skin_url: prefix + "/tinymce/skins/ui/oxide",
        content_css: prefix + "/tinymce/skins/ui/oxide/content.css",
        width: 800,
        height: 500,
        browser_spellcheck: true,
        contextmenu_never_use_native: true,
        contextmenu:
            "link linkchecker image editimage table spellchecker configurepermanentpen",
        promotion: false, // 是否显示升级按钮
        statusbar: false, // 是否显示底部状态栏
        resize: "both",
        media_live_embeds: true, // 上传视频后，是否回显视频
        image_advtab: true,
        branding: false,
        font_size_formats: "8px 10px 12px 14px 16px 18px 24px 36px 48px",
        indentation: "2em",
        plugins: [
            "advlist",
            "autolink",
            "link",
            "image",
            "lists",
            "charmap",
            "preview",
            "anchor",
            "pagebreak",
            "searchreplace",
            "wordcount",
            "visualblocks",
            "visualchars",
            "code",
            "fullscreen",
            "insertdatetime",
            "media",
            "table",
            "emoticons",
            "template",
            // "help",
        ],
        toolbar:
            "code undo redo |  styles | fontsize bold italic forecolor backcolor lineheight | alignleft aligncenter alignright alignjustify | " +
            "bullist numlist outdent indent | link image | print preview media fullscreen | " +
            "emoticons  ",

        // 默认菜单
        menu: {
            file: {
                title: "File",
                items: "newdocument restoredraft | preview | export print | deleteallconversations",
            },
            edit: {
                title: "Edit",
                items: "undo redo | cut copy paste pastetext | selectall | searchreplace",
            },
            view: {
                title: "View",
                items: "code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments",
            },
            insert: {
                title: "Insert",
                items: "image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor tableofcontents | insertdatetime",
            },
            format: {
                title: "Format",
                items: "bold italic underline strikethrough superscript subscript codeformat | styles blocks fontfamily fontsize align lineheight | forecolor backcolor | language | removeformat",
            },
            tools: {
                title: "Tools",
                items: "spellchecker spellcheckerlanguage | a11ycheck code wordcount",
            },
            table: {
                title: "Table",
                items: "inserttable | cell row column | advtablesort | tableprops deletetable",
            },
            // help: { title: "Help", items: "help" },
        },
        menubar: "file edit view insert format tools table ",
        paste_convert_word_fake_lists: false,
        images_upload_handler: (blobInfo: any, progress: any) => {
            return new Promise(async (resolve, reject) => {
                let file = blobInfo.blob();
                let url = "";
                try {
                    url = await upload([file]);
                } catch {
                    reject({ message: "HTTP Error", remove: true });
                }
                resolve(encodeURI2(url));
            });
        },

        file_picker_callback: (callback: any, value: any, meta: any) => {
            let input = document.createElement(
                "input",
            ) as HTMLInputElement | null;
            if (input) {
                input.setAttribute("type", "file");
                if (meta.filetype == "media") {
                    input.setAttribute("accept", "audio/*,video/*");
                } else if (meta.filetype == "image") {
                    input.setAttribute("accept", "image/*");
                }

                input.addEventListener("change", async (e) => {
                    let target: any = e.target;
                    const file = target.files[0];
                    let url = await upload([file]);
                    callback(url);
                    input = null;
                });
                input.click();
            }
        },
    };

    const options = Object.assign({}, defalutOptions, init);

    const value = computed({
        get() {
            return props.modelValue;
        },
        set(value) {
            emit("update:modelValue", value);
        },
    });
    onMounted(() => {
        tinymce.init({}); // 初始化富文本
    });
</script>

<style lang="scss">
    .tox-textarea-wrap {
        border-color: #eee;
        border-radius: 6px;
        border-style: solid;
        border-width: 1px;
        display: flex;
        flex: 1;
        overflow: hidden;
    }
</style>
